package com.zzl.study.sharding.algorithm.hint;

import org.apache.shardingsphere.sharding.api.sharding.hint.HintShardingAlgorithm;
import org.apache.shardingsphere.sharding.api.sharding.hint.HintShardingValue;

import java.util.*;

/**
 * @author: zhangzl
 * @date: 2022/7/17 12:00
 * @version: 1.0
 * @description: 书本表自定义类分片算法：hint策略，对书本表的region字段进行精准分片
 * A区的在分片0和1中进行查询，B区的在分片2和3中进行查询，C区的在分片4和5中进行查询
 */
public class BookHintShardingAlgorithm implements HintShardingAlgorithm<String> {

    /**
     * 配置的props属性
     */
    private Properties props;

    /**
     * 存放分区对应的分片下标的Map集合
     */
    private Map<String, Integer> hintValueMap = new HashMap<>();

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, HintShardingValue<String> shardingValue) {
        String logicTableName = shardingValue.getLogicTableName();
        List<String> result = new ArrayList<>();
        for (String value : shardingValue.getValues()) {
            Integer suffix = this.hintValueMap.get(value);
            result.add(logicTableName + "_" + suffix);
        }
        return result;
    }

    @Override
    public Properties getProps() {
        return this.props;
    }

    @Override
    public void init(Properties props) {
        this.props = props;
        hintValueMap.put("A区", 0);
        hintValueMap.put("B区", 1);
        hintValueMap.put("C区", 2);
        hintValueMap.put("D区", 3);
        hintValueMap.put("E区", 4);
        hintValueMap.put("F区", 5);
    }

}
